import { defineStore } from 'pinia'
import { ref } from 'vue'

const formatRouter = (routes, routeMap, routeList) => {
  routes && routes.forEach(item => {
    if ((!item.children || item.children.every(ch => ch.hidden)) && item.name !== '404' && !item.hidden) {
      if (item.meta && item.meta.title) {
        routeList.value.push({ label: item.meta.title, value: item.name })
      }
    }
    routeMap.value[item.name] = item
    if (item.children && item.children.length > 0) {
      formatRouter(item.children, routeMap, routeList)
    }
  })
}

const KeepAliveFilter = (routes, keepAliveRoutes) => {
  routes && routes.forEach(item => {
    // 子菜单中有 keep-alive 的，父菜单也必须 keep-alive，否则无效。这里将子菜单中有 keep-alive 的父菜单也加入。
    if ((item.children && item.children.some(ch => ch.meta.keepAlive) || (item.meta && item.meta.keepAlive))) {
      item.component && item.component().then(val => { 
        keepAliveRoutes.value.push(val.default.name) 
      })
    }
    if (item.children && item.children.length > 0) {
      KeepAliveFilter(item.children, keepAliveRoutes)
    }
  })
}

export const useHallRouterStore = defineStore('hallRouter', () => {
  const routes = ref([])
  const routeMap = ref({})
  const routeList = ref([])
  const keepAliveRoutes = ref([])
  const defaultRouter = ref("")

  const initHallRouter = async(routeDatas) => {
    formatRouter(routeDatas, routeMap, routeList)
    KeepAliveFilter(routeDatas, keepAliveRoutes)
    defaultRouter.value = routeDatas[0].children[0].name
    routes.value = routeDatas
    console.log("initHallRouter routes", routes.value)
    console.log("initHallRouter keepAliveRoutes",  keepAliveRoutes)
  }

  return {
    initHallRouter,
    defaultRouter,
    routes,
    routeMap,
    routeList,
    keepAliveRoutes
  }
})